# perf_cmp/parsers/lkp_compare_parser.py
from typing import List, Dict, Any
import re

class LkpCompareParser:
    def parse(self, text_output: str) -> List[Dict[str, Any]]:
        """
        Parses the text table output from 'lkp compare'.
        """
        comparison_results = []
        
        # Regex to capture the main data rows. It's designed to be robust and handle
        # integers, floats, and scientific notation (e.g., 2.345e+09).
        # It assumes the two values and the percentage change are always present.
        # It captures: 1: value_a, 2: percentage_delta, 3: value_b, 4: metric_name
        metric_line_re = re.compile(
            r"^\s*([\d.eE+-]+)\s+"  # Group 1: Value A (handles numbers like 702184, 34.85, 2.345e+09)
            r"(?:\S+\s+)?"          # Optional non-capturing group for %stddev column
            r"(-?[\d.]+)%\s+"       # Group 2: Percentage Change (e.g., '36', '-66')
            r"([\d.eE+-]+)\s+"      # Group 3: Value B
            r"(?:\S+\s+)?"          # Optional non-capturing group for %stddev column
            r"(.+)$"                # Group 4: The rest of the line is the metric name
        )

        # Flag to start processing only after the header separator "---" is found
        start_processing = False
        
        for line in text_output.strip().split('\n'):
            line = line.strip()
            if not line:
                continue

            if '----------------' in line:
                start_processing = True
                continue # Skip the separator line itself

            if not start_processing:
                continue # Skip header lines before the separator

            match = metric_line_re.match(line)
            if match:
                val_a_str, pct_delta_str, val_b_str, metric_name = match.groups()
                
                try:
                    # Convert captured strings to appropriate numeric types
                    val_a_float = float(val_a_str)
                    val_b_float = float(val_b_str)
                    pct_delta_float = float(pct_delta_str)

                    # Calculate absolute delta from the values
                    abs_delta = val_b_float - val_a_float

                    comparison_results.append({
                        "metric_name": metric_name.strip(),
                        "value_scenario_a": val_a_float,
                        "value_scenario_b": val_b_float,
                        "percentage_delta": pct_delta_float,
                        "absolute_delta": abs_delta 
                    })
                except (ValueError, TypeError) as e:
                    # Log a warning if a line looks like data but fails to parse/convert
                    print(f"Warning: Could not parse data row: '{line}'. Error: {e}")

        if not comparison_results:
             print("Warning: LkpCompareParser did not find any metric data rows to parse from the input.")
        
        return comparison_results
